﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ParamSetCollection.General.Parameters.Normal;
using ParamSetCollection.General.Logs;
using MainController.Hardware.PLC.MEGMEET.Communication;

namespace MainController.Hardware.PLC.MEGMEET.Datas.Groups
{
    class BitsGroup : ParamGroup
    {
        #region============================== 结构体 ====================================
        public struct ShortBits
        {
            public ShortBits(ushort initialBitValue)
            {
                this.bits = initialBitValue;
            }

            public bool this[int index]
            {
                get
                {
                    return (this.bits & (1 << index)) != 0;
                }

                set
                {
                    if (value)//如果value为true，就将bit设为1（打开）；否则设为0（关闭）。
                    {
                        this.bits |= (ushort)(1 << index);
                    }
                    else
                    {
                        this.bits &= (ushort)~(1 << index);
                    }
                }
            }

            public static implicit operator ShortBits(ushort from)
            {
                return new ShortBits(from);
            }

            public static implicit operator ushort(ShortBits from)
            {
                return from.bits;
            }

            private ushort bits;
        }
        #endregion=====================================================================

        #region============================== 变量 ====================================
        //public override event OnRenewParamListEventHandler OnRenewParamListEvent;

        bool renewLock = false;
        #endregion=====================================================================


        #region============================== 属性 ====================================
        #endregion=====================================================================


        #region============================= 内部函数 ================================
        private void BindingDataUnit(List<DataUnit> duList)
        {


        }

        #endregion====================================================================


        #region============================= 保护函数 ================================
        //修改data缓存值
        protected override void ChangeBuffer(string position, object value)
        {
            bool val =(bool)value;
            int[] posi = new int[2];
            string[] posi2;


            posi2 = position.Split('.');
            posi[0] = Convert.ToInt32(posi2[0]);
            //int _temp = Convert.ToInt32(posi2[1]);
            //posi[1] = _temp >= 8 ? _temp - 8 : _temp+8;

            posi[1] = Convert.ToInt32(posi2[1]);

            ushort temp = (ushort)(65535 - (ushort)Math.Pow(2, posi[1]));

            data[posi[0]] = (ushort)(data[posi[0]] & temp);

            if (val == true)
            {
                data[posi[0]] += (ushort)Math.Pow(2, posi[1]);
            }
        }
        #endregion====================================================================


        #region============================= 公开函数 ================================
        public BitsGroup(string paramType, string baseCode,  Dictionary<string, string> paramDic, string cfgPath, ushort[] dataBuf)
            : base(paramType, baseCode, "bit.cfg",  paramDic, cfgPath, dataBuf)
        {

        }

        //获取参数修改指令
        public override List<CommUnit> GetParamSetting(ref List<ParamUnit> paramList)
        {
            renewLock = true;
            List<CommUnit> cmdList = new List<CommUnit>();
            Dictionary<string, ushort> dataList = new Dictionary<string, ushort>();
            foreach (ParamUnit item in paramList)
            {
                if (m_paramDic.ContainsKey(item.Code))
                {
                    string[] str = m_paramDic[item.Code].Position.Split('.');
                    int _temp = Convert.ToInt32(str[1]);


                    m_paramDic[item.Code].Value = Boolean.Parse(item.Value).ToString();//修改成员值，产生修改信息

                    if (!item.DontRenewBufMark)
                        ChangeBuffer(str[0] + "." + str[1],  Convert.ToBoolean(m_paramDic[item.Code].Value));

                    if (dataList.ContainsKey(str[0]) == true)
                    {
                        dataList[str[0]] = data[Convert.ToInt32(str[0])];
                    }
                    else
                    {
                        dataList.Add(str[0], data[Convert.ToInt32(str[0])]);
                    }

                }
            }
            //获取写参数指令
            cmdList.AddRange(GetWriteDataCommands(dataList));

            renewLock = false;
            return cmdList;
        }

        //初始化系统参数
        public override List<CommUnit> InitCtx(object ctxData)
        {
            List<CommUnit> cmdList = new List<CommUnit>();
            Dictionary<string, ushort> dataList = new Dictionary<string, ushort>();

            Dictionary<string, bool> boolDic = ctxData as Dictionary<string, bool>;
            if (boolDic != null)
            {

                foreach (var key in boolDic.Keys)
                {
                    if (m_paramDic.ContainsKey(key))
                    {
                        string[] str = m_paramDic[key].Position.Split('.');
                        int _temp = Convert.ToInt32(str[1]);

                        m_paramDic[key].Value = boolDic[key].ToString();
                        ChangeBuffer(str[0] + "." + str[1], Convert.ToBoolean(m_paramDic[key].Value));

                        if (dataList.ContainsKey(str[0]) == true)
                        {
                            dataList[str[0]] = data[Convert.ToInt32(str[0])];
                        }
                        else
                        {
                            dataList.Add(str[0], data[Convert.ToInt32(str[0])]);
                        }
                    }
                }
                cmdList.AddRange(GetWriteDataCommands(dataList));
            }

            return cmdList;
        }



        //获取初始化指令
        public override List<CommUnit> GetInitCmdList()
        {
            List<CommUnit> cmdList = new List<CommUnit>();
            Dictionary<string, ushort> dataList = new Dictionary<string, ushort>();
            foreach (string item in m_paramDic.Keys)
            {
                string[] str = m_paramDic[item].Position.Split('.');


                if (dataList.ContainsKey(str[0]) == true)
                {
                    dataList[str[0]] = data[Convert.ToInt32(str[0])];
                }
                else
                {
                    dataList.Add(str[0], data[Convert.ToInt32(str[0])]);
                }
            }

            //获取写参数指令
            cmdList.AddRange(GetWriteDataCommands(dataList));
            return cmdList;
        }

        //更新参数，用于plc参数监控
        public override void InputNewDatas(ushort[] data)
        {
            if (renewLock == true)
            {
                return;
            }
            this.m_msgLock = true;
            Queue<ParamUnit> puQ = new Queue<ParamUnit>();
            foreach (string item in m_paramDic.Keys)
            {
                string[] _str = null;
                ushort _data = 0;
                _str = m_paramDic[item].Position.Split('.');


                _data = (ushort)(data[Convert.ToInt32(_str[0])]);
                





                string v = Convert.ToBoolean(((_data << (15 - Convert.ToInt32(_str[1]))) & 0xffff) >> 15).ToString();
                if (m_paramDic[item].Value != v)
                {
                    m_paramDic[item].Value = v;
                    ParamUnit pu = m_paramDic[item].TransferToRemoteUnit();
                    pu.Code = m_baseName + "." + pu.Code;
                    puQ.Enqueue(pu);
                }
                else
                {
                    m_paramDic[item].Value = v;
                }

            }

            //if (puQ.Count > 0 && OnRenewParamListEvent != null)
            //{
            //    OnRenewParamListEvent(puQ);
            //}

            puQ = null;
            m_msgLock = false;

        }

        //获取写参数指令
        public override List<CommUnit> GetWriteDataCommands(Dictionary<string, ushort> dataList = null, List<ParameterUnit> paramList = null)
        {
            List<CommUnit> cmdList = new List<CommUnit>();
            if (dataList != null)
            {
                foreach (string item in dataList.Keys)
                {
                    cmdList.Add(new CommUnit(CommAction.WriteMultReg, Convert.ToUInt16(item), new ushort[1] { dataList[item] }));
                }
            }
            return cmdList;
        }


        #endregion====================================================================


        #region============================= 消息响应 ================================
        #endregion====================================================================
    }
}
